

//
//  WorkTimeViewController.m
//  EcmDoctor
//
//  Created by Mac on 16/2/22.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "WorkTimeViewController.h"
#import "AppUtils.h"
#import "DetalWTTableViewCell.h"
#import "DetalWTM.h"
@interface WorkTimeViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    
    __weak IBOutlet UIView *_detailView;
    __weak IBOutlet UIScrollView *_timeSV;
    __weak IBOutlet NSLayoutConstraint *width2;
    __weak IBOutlet NSLayoutConstraint *width1;
    UIImageView *_leftarrow;
    NSMutableArray *_dataAry;
    NSMutableArray *_phdataAry;
    NSMutableArray *_addataAry;
   // __weak IBOutlet UIScrollView *_detalScV;
    UIImageView *_rightarrow;
    UILabel *_bzLabel;
    UIScrollView *_detalScV;
    NSArray *_keyStrAry;
}
@end

@implementation WorkTimeViewController

- (void)viewDidLoad {
//    self.navigationController.navigationBar.translucent = NO;
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [AppUtils getBackground];
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"我的工作时间"];
    [_detailView removeFromSuperview];
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 164, kScreenWidth, kScreenHeight-164)];
    view.backgroundColor=[UIColor clearColor];
    [self.view addSubview:view];
    _detalScV=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-164)];
    _detalScV.showsVerticalScrollIndicator=NO;
    _detalScV.showsHorizontalScrollIndicator=NO;
    _detalScV.backgroundColor=[UIColor clearColor];
    _detalScV.pagingEnabled=YES;
    _detalScV.tag=918;
    _detalScV.delegate=self;
    _detalScV.contentSize=CGSizeMake(kScreenWidth*7, kScreenHeight-164);
    [view addSubview:_detalScV];
    //加载工作时间详情页面
    [self getdetalWorkTime];
    width1.constant=kScreenWidth/2;
    width2.constant=kScreenWidth/2;
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
    _timeSV.contentSize=CGSizeMake(kScreenWidth/3*7, 60);
    //获取时间
    [self getdate];
    //请求数据
    _keyStrAry=@[@"getPhoneWorkTime",@"getAddTimeWorkTime"];
   
    [self reloadDataWith:_keyStrAry[0]];
    
    
   }
-(void)reloadDataWith:(NSString *)key
{
    NSString *docId= [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    [DetalWTM requetDoctorWorkTimeWith:docId And:key success:^(NSArray *detalwtmAry) {
        if([key isEqualToString:@"getPhoneWorkTime"])
        {
            _phdataAry=[NSMutableArray arrayWithArray:detalwtmAry];
            _dataAry=[NSMutableArray arrayWithArray:_phdataAry];
            [self tableViewRelod];
            
        }
        else
        {
            _addataAry=[NSMutableArray arrayWithArray:detalwtmAry];
            _dataAry=[NSMutableArray arrayWithArray:_addataAry];
            [self tableViewRelod];
        }
       
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];

    
}
-(void)tableViewRelod
{
    for(int i=0;i<7;i++)
    {
        UITableView *tableView=(UITableView *)[_detalScV viewWithTag:2001+i];
        [tableView reloadData];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (_dataAry.count != 0) {
//        
//    } else
//        return 0;
    
    
    DetalWTM *detalwtm=_dataAry[tableView.tag-2001];
    
    if([detalwtm.ishave isEqualToString:@"0"])
    {
        UILabel *tsLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 10, kScreenWidth, 20)];
        tsLabel.backgroundColor=[UIColor clearColor];
        tsLabel.textAlignment= NSTextAlignmentCenter;
        tsLabel.text=@"您今天没有合适的工作时间";
        tsLabel.tag=tableView.tag+1000;
        tsLabel.font=[UIFont systemFontOfSize:14];
        tsLabel.textColor=[UIColor lightGrayColor];
        [tableView addSubview:tsLabel];
        
        return 0;
    }
    else
    {
        UILabel *label=(UILabel *)[tableView viewWithTag:tableView.tag+1000];
        [label removeFromSuperview];
        return detalwtm.detaileInfosListAry.count;
    }
}

static int sw=234;
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetalWTM *detalwtm=_dataAry[tableView.tag-2001];
    DetaileInfosList *detailin=detalwtm.detaileInfosListAry[indexPath.row];
    UITableViewCell *cell;
    DetalWTTableViewCell*dtwtcell=[tableView dequeueReusableCellWithIdentifier:@"detalwt" forIndexPath:indexPath];
    if(sw==234)
    {
        dtwtcell.btlabel.text=@"电话咨询";
    }
    else
    {
        dtwtcell.btlabel.text=@"门诊预约";
        
    }
    dtwtcell.timeLabel.text=detailin.time_info;
    dtwtcell.numLabel.text=[NSString stringWithFormat:@"%d/%@",(detailin.all_num.intValue-detailin.left_num.intValue),detailin.all_num];
    dtwtcell.resLabel.text=[NSString stringWithFormat:@"剩余%@人",detailin.left_num];
    dtwtcell.backgroundColor=[UIColor clearColor];
    dtwtcell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell=dtwtcell;
    return cell;
}
-(void)getdetalWorkTime
{
  
    for(int i=0;i<7;i++)
    {
        UITableView *detaltv=[[UITableView alloc]initWithFrame:CGRectMake(kScreenWidth*i, 0, kScreenWidth,kScreenHeight-164) style:UITableViewStylePlain];
       
        detaltv.dataSource=self;
        detaltv.delegate=self;
        detaltv.tag=2001+i;
        detaltv.bounces=NO;
        detaltv.showsHorizontalScrollIndicator=NO;
        detaltv.showsVerticalScrollIndicator=NO;
        detaltv.backgroundColor=[UIColor clearColor];
        [detaltv registerNib:[UINib nibWithNibName:@"DetalWTTableViewCell" bundle:nil] forCellReuseIdentifier:@"detalwt"];
        detaltv.rowHeight=100;
        detaltv.pagingEnabled=YES;
        detaltv.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_detalScV addSubview:detaltv];
        
    }
}
-(void)changeToNavRootController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getdate
{
    _leftarrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64+64, 8, 12)];
    _rightarrow=[[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth-8, 64+64, 8, 12)];
    
    NSDateFormatter *datef =[[NSDateFormatter alloc]init];
    [datef setDateFormat:@"yyyy年MM月dd日"];
  
    for(int i=1;i<8;i++)
    {
        NSDate * date1 = [NSDate dateWithTimeIntervalSinceNow:3600*24*(i-1)];
          NSString * _strData = [datef stringFromDate:date1];
        UILabel *timeLabel=[[UILabel alloc]initWithFrame:CGRectMake((i-1)*kScreenWidth/3, 0, kScreenWidth/3, 58)];
        if(i==1)
        { timeLabel.textColor=[UIColor colorWithRed:201/255.0 green:142/255.0 blue:2/255.0 alpha:1];
            _bzLabel=[[UILabel alloc]initWithFrame:CGRectMake((i-1)*kScreenWidth/3, 58, kScreenWidth/3, 2)];
            _bzLabel.backgroundColor=[UIColor colorWithRed:201/255.0 green:142/255.0 blue:2/255.0 alpha:1];
            [_timeSV addSubview:_bzLabel];

        }
        else
            timeLabel.textColor=[UIColor colorWithRed:111/255.0 green:110/255.0 blue:110/255.0 alpha:1];
        timeLabel.numberOfLines=2;
        timeLabel.tag=1000+i;
        timeLabel.textAlignment=NSTextAlignmentCenter;
        timeLabel.font=[UIFont systemFontOfSize:12];
        timeLabel.userInteractionEnabled=YES;
        NSString *str=[self getDateAndWeek:date1];
        [timeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)]];
        timeLabel.text=[NSString stringWithFormat:@"%@\n%@",str,_strData];
        [_timeSV addSubview:timeLabel];
    }
    [self.view addSubview:_leftarrow];
    [self.view addSubview:_rightarrow];
    _rightarrow.image=[UIImage imageNamed:@"arrow_right"];
    _leftarrow.image=[UIImage imageNamed:@"arrow_left"];
    _rightarrow.alpha=1;
    _leftarrow.alpha=0;
}
static int bz=1001;
-(void)tapView:(UITapGestureRecognizer*)tap
{
    if(bz!=tap.view.tag)
    {
        [self liandongWith:(int)tap.view.tag];
        [UIView animateWithDuration:0.3 animations:^{
           _detalScV.contentOffset=CGPointMake(kScreenWidth*((int)tap.view.tag-1001), 0);
        }];
        
    }
    
}
-(void)liandongWith:(int)num
{
    if(num!=bz)
{
    UILabel *beflabel=(UILabel *)[_timeSV viewWithTag:bz];
    beflabel.textColor=[UIColor colorWithRed:111/255.0 green:110/255.0 blue:110/255.0 alpha:1];
    UILabel *currentLabel=(UILabel *)[_timeSV viewWithTag:num];
    currentLabel.textColor=[UIColor colorWithRed:201/255.0 green:142/255.0 blue:2/255.0 alpha:1];
    
    bz=num;
    
    if(num>=1002&&num<1007)
    {
        [UIView animateWithDuration:0.3 animations:^{
           
            _timeSV.contentOffset=CGPointMake(kScreenWidth/3*(num-1000-2), 0);
        }];
        
        [UIView animateWithDuration:0.35 animations:^{
            _bzLabel.frame=CGRectMake((num-1000-1)*kScreenWidth/3, 58, kScreenWidth/3, 2);
           
        }];

    }
    else
        [UIView animateWithDuration:0.35 animations:^{
            _bzLabel.frame=CGRectMake((num-1000-1)*kScreenWidth/3, 58, kScreenWidth/3, 2);
        }];
}
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     if(![scrollView isMemberOfClass:[UITableView class]])
     {
     _leftarrow.alpha=scrollView.contentOffset.x>0;
         if(scrollView.tag==918)
         {
        _rightarrow.alpha=scrollView.contentOffset.x<(4*kScreenWidth);
         }
         else
     _rightarrow.alpha=scrollView.contentOffset.x<(4*(kScreenWidth/3));
     }
   
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(![scrollView isMemberOfClass:[UITableView class]])
    {
      
        if(scrollView.tag==918)
        {
            int a=(int )scrollView.contentOffset.x/kScreenWidth;
            [self liandongWith:(a+1001)];
            
        }
       
    }
}

-(NSString *)getDateAndWeek:(NSDate *)date{
    
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear|NSWeekdayCalendarUnit;
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [cal components:unitFlags fromDate:date];
    
    NSArray *weekArr = [NSArray arrayWithObjects:@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六", nil];
    NSString *weekStr = [weekArr objectAtIndex:(int)comps.weekday-1];
    
    return weekStr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (IBAction)topSwitch:(UIButton *)sender {
    if(sender.tag!=sw)
    {
        UIButton *bfbtn=(UIButton*)[self.view viewWithTag:sw];
        if(sender.tag==234)
        {
            if(_phdataAry.count!=0)
            _dataAry=[NSMutableArray arrayWithArray:_phdataAry];
            else
                 [self reloadDataWith:_keyStrAry[0]];
            
        }
        else
        {
            if(_addataAry.count!=0)
            _dataAry=[NSMutableArray arrayWithArray:_addataAry];
            else
            {
                [self reloadDataWith:_keyStrAry[1]];
            }
        }
    
        sw=(int)sender.tag;
    
        [bfbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        bfbtn.backgroundColor=[UIColor colorWithRed:123/255.0 green:103/255.0 blue:94/255.0 alpha:1];
        [sender setTitleColor:[UIColor colorWithRed:255/255.0 green:204/255.0 blue:102/255.0 alpha:1] forState:UIControlStateNormal];
        sender.backgroundColor=[UIColor colorWithRed:42/255.0 green:18/255.0 blue:6/255.0 alpha:1];
        
        _timeSV.contentOffset=CGPointMake(0, 0);
        UILabel *bflabel=(UILabel *)[_timeSV viewWithTag:bz];
        bflabel.textColor=[UIColor colorWithRed:111/255.0 green:110/255.0 blue:110/255.0 alpha:1];
        UILabel *filabel=(UILabel *)[_timeSV viewWithTag:1001];
        filabel.textColor=[UIColor colorWithRed:201/255.0 green:142/255.0 blue:2/255.0 alpha:1];
        bz=1001;
       [UIView animateWithDuration:0.3 animations:^{
   _bzLabel.frame=CGRectMake(0, 58, kScreenWidth/3, 2);
      _timeSV.contentOffset=CGPointMake(0, 0);
      _detalScV.contentOffset=CGPointMake(0, 0);
      }];
    }
}
@end
